<!-- 分包商选择 -->
<template>
  <!-- 支持输入的选择框 -->
  <a-auto-complete
    v-if="isInput"
    v-bind="$attrs"
    v-on="$listeners"
    v-model="currentValue"
    :placeholder="placeholder"
    :filter-option="filterOption"
    :dataSource="Subcontractor"
  ></a-auto-complete>
  <!-- 普通选择框 -->
  <a-select
    v-else
    v-bind="$attrs"
    v-on="$listeners"
    :placeholder="placeholder"
    v-model="currentValue"
    @change="handleBindName"
    :option-filter-prop="optionFilterProp"
    :filter-option="filterOption"
  >
    <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-else v-for="i in Subcontractor" :key="i.subContractorId" :value="i.subContractorId"
      >{{ i.name }}
    </a-select-option>
  </a-select>
</template>
<script>
import { getSubcontractor } from '@/api/businessAffairs/sml'

export default {
  name: 'SelectSubcontractor',
  props: {
    bindName: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 表单是否可输入
    isInput: {
      type: Boolean,
      default: () => false
    },
    // v-model绑定的数据
    value: {
      type: [Array, String, Object]
    },
    // 需要联动的表单，
    form: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 需要联动的表单名
    keyValue: {
      type: String,
      default: () => 'projectId'
    },
    // 联动表单值改变时是否清空当前表单值
    isClear: {
      type: Boolean,
      default: () => true
    },
    // 项目id
    projectId: {
      type: String,
      default: () => ''
    },
    // placeholder
    placeholder: {
      type: String,
      default: () => '请选择'
    },
    // 搜索时过滤对应的 option 属性，如设置为 children 表示对内嵌内容进行搜索,否则为value
    optionFilterProp: {
      type: String,
      default: () => 'children'
    },
    //如果是编辑，第一次不要重置绑定的值。。。。
    isEdit: {
      type: Boolean,
      default: () => false
    },
    //额外的列表选项
    extraSubcontractor: {
      type: Object,
      default: () => null
    },
    //是否需要传此参数
    isAll:{
      type:Boolean,
      default: () => false
    }
  },
  data() {
    return {
      isCanClear: !this.isEdit,
      fetching: false,
      Subcontractor: []
    }
  },
  methods: {
    handleBindName(v) {
      let res = this.Subcontractor.find((item) => item.subContractorId === v)
      if (res) {
        this.$emit('update:bindName', res.name)
          this.$emit('selectChange', res)
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * 获取列表
     */
    getSubcontractorList(params) {
      if(/[A-Za-z]/.test(params.query.branchComIds[0])) return // 包含字母的id不是项目，需排除
      let data = {
        id: params.query.branchComIds[0]
      }
      if(this.isAll){
        data.isAll = true;
      }
      this.fetching = true
      getSubcontractor(data)
        .then((res) => {
          this.fetching = false
          if (res.code === 200) {
            res.data.forEach((item) => {
              item.text = item.name
              item.value = item.subContractorId
            })
            this.Subcontractor = res.data
            // 若有额外选项则添加到末尾
            this.extraSubcontractor && this.Subcontractor.push(this.extraSubcontractor)
            this.$emit('update:list', this.Subcontractor)
            this.$emit(
              'update:option',
              this.Subcontractor.find((item) => item.subContractorId === this.currentValue)
            )
            this.$emit(
              'getOption',
              this.Subcontractor.find((item) => item.subContractorId === this.currentValue)
            )
          }
        })
        .catch((res) => {
          this.fetching = false
        })
    }
  },
  computed: {
    // 需要联动的表单值, keyValue可以是aa.bb.cc的形式，对应的绑定值也是对象，取得该对象obj.aa.bb.cc的值
    attr() {
      let attrValue
      const keys = this.keyValue.split('.')
      const findValueFromKeys = (data, key) => {
        if(data instanceof Object && keys.some(k => k === key)){
          return findValueFromKeys(data[key], keys[keys.findIndex(k => k === key) + 1])
        }
        return data
      }
      if(keys && !!keys.length){
        attrValue = findValueFromKeys(this.form, keys[0])
      }
      return attrValue
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value || void 0
      },
      set: function (value) {
        this.$emit('input', value)
      }
    }
  },
  mounted() {
    let val = this.attr || this.projectId
    val && this.getSubcontractorList({ query: { branchComIds: [val] } })
  },
  watch: {
    currentValue(value) {
      this.$nextTick(() => {
        if (value && this.Subcontractor.length > 0) {
          this.$emit(
            'update:option',
            this.Subcontractor.find((item) => item.subContractorId === value)
          )
          this.$emit(
            'getOption',
            this.Subcontractor.find((item) => item.subContractorId === this.currentValue)
          )
        }
      })
    },
    projectId(val) {
      // 清空表单
      if (this.isClear) {
        this.currentValue = void 0
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      }
      // 清空表单
      if (this.isEdit && this.isCanClear) {
        this.currentValue = void 0
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      } else {
        this.isCanClear = true
      }
      // 重置列表
      this.Subcontractor = []
      val && this.getSubcontractorList({ query: { branchComIds: [val] } })
    },
    // 监听联动表单值重置项目列表
    attr(val) {
      // 清空表单
      if (this.isClear) {
        this.currentValue = void 0
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      }
      // 清空表单
      if (this.isEdit && this.isCanClear) {
        this.currentValue = void 0
        this.$emit('resetSelf') // 在搜索组件(SearchData)中重置自身的值
      } else {
        this.isCanClear = true
      }
      // 重置列表
      this.Subcontractor = []
      val && this.getSubcontractorList({ query: { branchComIds: [val] } })
    }
  }
}
</script>
